import 'package:flutter/material.dart';
import 'package:safety_platform/models/hidden_danger.dart';
import 'package:safety_platform/models/situation.dart';
import 'dart:io';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:safety_platform/utils.dart';
import 'package:safety_platform/pages/gallery.dart';
import 'package:safety_platform/components/attachment.dart';
import 'package:safety_platform/theme.dart' show backgroundTitle;

class HiddenDangerDetailPage extends StatefulWidget {
  final HiddenDanger hiddenDanger;
  HiddenDangerDetailPage(this.hiddenDanger);

  @override
  State<StatefulWidget> createState() =>
      _HiddenDangerDetailPageState(this.hiddenDanger);
}

class _HiddenDangerDetailPageState extends State<HiddenDangerDetailPage> {
  HiddenDanger hiddenDanger;

  _HiddenDangerDetailPageState(this.hiddenDanger);
  Widget build(BuildContext context) {
    print('detai: ${hiddenDanger.toJson()}');
    return Scaffold(
      resizeToAvoidBottomPadding: false,
      appBar: AppBar(
        title: new Text("隐患详情"),
        elevation: 0,

        //     leading: appLeading(context),
        backgroundColor: Color.fromARGB(255, 27, 130, 210),
        centerTitle: true, //设置标题是否局中
      ),
      body: WillPopScope(
          onWillPop: () {
            Navigator.of(context).pop(hiddenDanger);
            return Future.value(false);
          },
          child: SingleChildScrollView(child: _body(context))),
      // bottomNavigationBar: _bootomNavigationBar(context),
    );
  }

  // Widget _bootomNavigationBar(BuildContext context) {
  //   // if (_task != null && _task.status == 'pending') {
  //   return Container(
  //       width: MediaQuery.of(context).size.width,
  //       height: 48,
  //       color: Colors.white,
  //       child: Button(
  //         loading: false,
  //         buttonColor: Colors.white,
  //         onPressed: () {
  //           // _submit();
  //           Navigator.of(context)
  //               .push(MaterialPageRoute(
  //                   builder: (_) =>
  //                       HiddenDangerRectifyPage(hiddenDanger: hiddenDanger)))
  //               .then((hd) {
  //             if (hd != null) {
  //               setState(() {
  //                 this.hiddenDanger = hd;
  //               });
  //             }
  //           });
  //         },
  //         text: '隐患整改',
  //         textSize: 18,
  //         textColor: Color.fromARGB(255, 27, 130, 210),
  //       )
  //       // child: RaisedButton(
  //       //   color: Colors.white,
  //       //   onPressed: () {
  //       //     print('提交任务');
  //       //     _submit();
  //       //   },
  //       //   child: Text(
  //       //     '提交',
  //       //     style: TextStyle(
  //       //       color: Color.fromARGB(255, 27, 130, 210),
  //       //       fontSize: 18,
  //       //     ),
  //       //   ),
  //       // ),
  //       );
  //   // }
  //   return null;
  // }

  _buildRow(String title, String value) {
    if (value == null || value == 'null') {
      value = '';
    }
    return Container(
      padding: EdgeInsets.all(16.0),
      decoration: BoxDecoration(
        color: Colors.white,
        border: Border(
          bottom: BorderSide(
            width: 0.5,
            color: Color.fromARGB(255, 241, 241, 241),
          ),
        ),
      ),
      child: Row(
        children: <Widget>[
          Expanded(
            flex: 1,
            child: Text(title),
          ),
          Expanded(
            flex: 2,
            child: Text(
              value,
              textAlign: TextAlign.right,
              overflow: TextOverflow.ellipsis,
              style: TextStyle(color: Colors.grey),
            ),
          )
        ],
      ),
    );
  }

  _gallery(BuildContext context) {
    if (hiddenDanger.attachments != null &&
        hiddenDanger.attachments.length > 0) {
      List<Widget> children = hiddenDanger.attachments.map((attachment) {
        Widget child;
        if (attachment.localPath != null) {
          child = Image.file(
            File(attachment.localPath),
            fit: BoxFit.fill,
          );
        } else {
          if (attachment.url != null) {
            child = CachedNetworkImage(
              imageUrl: attachment.url,
              placeholder: Center(
                child: SpinKitCircle(
                    size: 32, color: Theme.of(context).primaryColor),
              ),
              errorWidget: new Icon(Icons.error),
              fit: BoxFit.fill,
            );
          }
        }
        return InkWell(
          onTap: () {
            print("ONONONONONONONONONONONONO ");
            List<String> urls = hiddenDanger.attachments.map((hd) {
              return hd.url;
            }).toList();
            Navigator.of(context).push(
                MaterialPageRoute(builder: (context) => GalleryPage(urls)));
          },
          child: Container(
            child: child,
            padding: EdgeInsets.all(8),
            height: 100,
            width: 100,
          ),
        );
      }).toList();

      return Container(
        margin: EdgeInsets.only(bottom: 8),
        padding: EdgeInsets.symmetric(horizontal: 8),
        width: MediaQuery.of(context).size.width,
        decoration: BoxDecoration(
          color: Colors.white,
        ),
        child: SingleChildScrollView(
          scrollDirection: Axis.horizontal,
          child: Row(
            mainAxisAlignment: MainAxisAlignment.start,
            mainAxisSize: MainAxisSize.max,
            children: children,
          ),
        ),
      );
    }
    return Container();
  }

  Widget _buildVerificationWidget(HiddenDanger hiddenDanger) {
    print('hd status ${hiddenDanger.status}');
    if (hiddenDanger.status == 'verified') {
      return Column(
        children: <Widget>[
          backgroundTitle('验收信息'),
          _buildRow('验收备注', '${hiddenDanger.memo??''}'),
          AttachmentPreviewGallery(
            attachments: hiddenDanger.verifiedImages,
            collapseLabel: '查看验收照片',
          )
          
        ],
        crossAxisAlignment: CrossAxisAlignment.start,
      );
    }
    return Container();
  }

  Widget _buildRectifyWidget(HiddenDanger hiddenDanger) {
    return Column(
      children: <Widget>[
        backgroundTitle('整改信息'),
        _buildRow('整改限定时间', hiddenDanger.retifyDate ?? ''),
        _buildRow('整改预算', '${hiddenDanger.rectificationBudget.toString()} 元'),
        _buildRow('整改实际花费', '${hiddenDanger.rectificationCost.toString()} 元'),
        AttachmentPreviewGallery(
          attachments: hiddenDanger.attachments,
          collapseLabel: '查看整改报告照片',
        )
      ],
      crossAxisAlignment: CrossAxisAlignment.start,
    );
  }

  Widget _buildSituation(HiddenDanger hiddenDanger) {
    return Column(
      children: <Widget>[
        backgroundTitle('存在的问题'),
        ListView.builder(
          
          physics: NeverScrollableScrollPhysics(),
          shrinkWrap: true,
          itemCount: hiddenDanger.situations.length,
          itemBuilder: (context, index) => _situationItem(context, index),
        ),
        DecoratedBox(
          decoration: BoxDecoration(
            border: Border(top: BorderSide(
              width: 0.5,
              color: Color.fromARGB(255, 241, 241, 241),
            ))
          ),
          child: 
          AttachmentPreviewGallery(
            attachments: hiddenDanger.attachments,
            collapseLabel: '查看问题照片',
          ),
        )
      ],
      crossAxisAlignment: CrossAxisAlignment.start,
    );
  }

  Widget _situationItem(BuildContext context, int index) {
    Situation situation = hiddenDanger.situations[index];
    List<Widget> children = [
      Flexible(
        flex: 1,
        child: Text(
          situation.content,
          // softWrap: false,
          overflow: TextOverflow.fade,
          maxLines: 8,
          style: Theme.of(context).textTheme.subhead,
        ),
      ),
    ];

    children.add(Padding(
      padding: EdgeInsets.symmetric(vertical: 8),
      child: Text(
        '整改措施',
        style: TextStyle(
          fontSize: 12,
          fontWeight: FontWeight.w600,
          color: Theme.of(context).disabledColor,
        ),
      ),
    ));
    children.add(
      Text(
        situation.improvement,
        style: TextStyle(
          fontSize: 12,
          color: Theme.of(context).disabledColor,
        ),
      ),
    );

    return DecoratedBox(
      decoration: BoxDecoration(
          color: Colors.white,
          border: Border(
              bottom: BorderSide(
            width: 0.5,
            color: Color.fromARGB(251, 241, 241, 241),
          ))),
      child: Container(
        padding: EdgeInsets.fromLTRB(16, 8, 16, 8),
        // height: 80,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          mainAxisSize: MainAxisSize.min,
          children: children,
        ),
      ),
    );
  }

  _body(BuildContext context) {
    return Container(
      // color: Colors.red,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          // _gallery(context),
          _buildRow('隐患编号', '${hiddenDanger.id}'),
          _buildRow('隐患状态', hiddenDangerStatusFromCode(hiddenDanger.status)),
          _buildRow('检查类型', hiddenDangerSourceFormCode(hiddenDanger.source)),
          _buildRow('隐患分类', '${hiddenDanger.classification.name}'),
          _buildRow('隐患级别', hiddenDangerGradeCodeToText(hiddenDanger.grade)),
          _buildRow('隐患部位', '${hiddenDanger.risk.name}'),
          _buildRow('提交时间', formatDate(hiddenDanger.created)),
          _buildSituation(hiddenDanger),
          _buildRectifyWidget(hiddenDanger),
          _buildVerificationWidget(hiddenDanger),
          // _buildRow('整改日期', '整改日期'),
          // _buildRow(
          //     '检查人员',
          //     hiddenDanger.createUser == null
          //         ? ''
          //         : '${hiddenDanger.createUser.screenName}'),
          // Row(children: <Widget>[
          //   Expanded(
          //     child: Container(
          //       padding: EdgeInsets.all(16.0),
          //       decoration: BoxDecoration(
          //         color: Colors.white,
          //         border: Border(
          //           bottom: BorderSide(
          //             width: 0.5,
          //             color: Color.fromARGB(255, 241, 241, 241),
          //           ),
          //         ),
          //       ),
          //       child: Column(
          //         crossAxisAlignment: CrossAxisAlignment.start,
          //         mainAxisSize: MainAxisSize.max,
          //         children: <Widget>[
          //           Text('隐患描述'),
          //           Padding(
          //             child: Text(
          //               '${hiddenDanger.memo}',
          //               textAlign: TextAlign.left,
          //               // overflow: TextOverflow.ellipsis,
          //               style: TextStyle(color: Colors.grey),
          //             ),
          //             padding: EdgeInsets.only(top: 4),
          //           ),
          //         ],
          //       ),
          //     ),
          //   ),
          // ])
          // _buildRow('隐患描述', '${hiddenDanger.memo}')
        ],
      ),
    );
  }
}
